package com.yao.longhan.utils;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader;

import java.util.Map;

/**
 * 说明：
 * <p>
 * 参数：
 * <p>
 * 来源：
 * <p>
 * Created by heyao on 2017/5/25.
 */

public class LruImageCache implements ImageLoader.ImageCache {
    private static LruCache<String, Bitmap> mMemoryCache;
    private static LruImageCache lruImageCache = null;

    private LruImageCache() {
        // Get the Max available memory
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 8;
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getRowBytes() * bitmap.getHeight();
            }
        };
    }

    @Override
    public Bitmap getBitmap(String url) {
        return mMemoryCache.get(url);
    }

    public void clearBitmap(String url) {
        Map<String, Bitmap> snapshot = mMemoryCache.snapshot();
        for (String key : snapshot.keySet()) {
            if (key.contains(url)) {
                mMemoryCache.remove(key);
            }
        }
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        if (mMemoryCache.get(url) == null) {
            mMemoryCache.put(url, bitmap);
        }
    }

    public static LruImageCache instance() {
        if (lruImageCache == null) {
            synchronized (LruImageCache.class) {
                if (lruImageCache == null) {
                    lruImageCache = new LruImageCache();
                }
            }
        }
        return lruImageCache;
    }
}
